package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    //    进行过滤器的初始化
    public void init(FilterConfig config) throws ServletException {
    }

    //销毁过滤器
    public void destroy() {
    }

    //过滤的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        将request和response进行类型转换
        HttpServletRequest req = (HttpServletRequest) request;
//        ServletResponse resp = (ServletResponse) response;
//        将【登录、注册相关资源】和【静态资源】直接放行
        //1.在数组中存储登陆和注册相关的资源路径
        String[] urls = {"/login.jsp", "/register.jsp", "/css", "/images", "/js",
                "/login", "/user", "/verifyCode"};
        //2.获取当前访问的资源路径
        String uri = req.getRequestURI();
//3.遍历数组，获取到每一个需要放行的资源路径
        for (String u : urls) {
//4.判断当前访问的资源路径字符串是否包含要放行的的资源路径字符串
/*
比如当前访问的资源路径是 /brand-demo/login.jsp
而字符串 /brand-demo/login.jsp 包含了字符串 /login.jsp ，所以就需要放行
*/
            if (uri.contains(u)) {
//找到了，放行
                chain.doFilter(req, response);
//不再继续向下走了,这里要return
                return;
            }
        }
////情况二：对于下面不能直接放行的资源，需要判断是否是已经登录
////1. 判断session中是否有user
//        HttpSession session = req.getSession();
//        Object user = session.getAttribute("LOGIN_USER");
////2. 判断user是否为null
//        if (user != null) {
//// 已经登录,放行
//            chain.doFilter(req, response);
//        } else {
//// 没有登陆，存储提示信息，跳转到登录页面
//            req.setAttribute("LOGIN_MSG", "您尚未登陆！");
//            req.getRequestDispatcher("/login.jsp").forward(req, response);
//        }
//    }


    ////1. 判断session中是否有user
    HttpSession session = req.getSession();
    User user = (User) session.getAttribute("LOGIN_USER");
    //2. 判断user是否为null
        if(user !=null)

    {
//// 已经登录,放行
        chain.doFilter(req, response);
    }else

    {
//// 没有登陆，存储提示信息，跳转到登录页面
        req.setAttribute("LOGIN_MSG", "您尚未登陆！");
        req.getRequestDispatcher("/login.jsp").forward(req, response);
        return;
    }
}
}

